<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div class="topTitle">线索信息</div>
            <div class="basin-info">
              <div style="display: flex; align-items: center">
                <div class="basin-left">
                  <div class="box">
                    <span>线索名称：</span>
                    <span>{{ dispatchInfo.clueName }}</span>
                  </div>
                  <div class="box">
                    <span>接收人：</span>
                    <span>{{ dispatchInfo.receiveUser }}</span>
                  </div>
                  <div class="box">
                    <span>姓名：</span>
                    <span>{{ dispatchInfo.userName }}</span>
                  </div>
                  <div class="box">
                    <span>联系方式：</span>
                    <span>{{ dispatchInfo.phone }}</span>
                  </div>
                  <div class="box">
                    <span>证件类型：</span>
                    <span>{{ dispatchInfo.idTypeName }}</span>
                  </div>
                </div>
                <div class="basin-right">
                  <div class="box">
                    <span>移交人：</span>
                    <span>{{ dispatchInfo.transferUser }}</span>
                  </div>
                  <div class="box">
                    <span>接收时间：</span>
                    <span>{{ dispatchInfo.receiveTime }}</span>
                  </div>
                  <div class="box">
                    <span>单位：</span>
                    <span>{{ dispatchInfo.dept }}</span>
                  </div>
                  <div class="box">
                    <span>提交时间：</span>
                    <span>{{ dispatchInfo.commitTime }}</span>
                  </div>
                  <div class="box">
                    <span>证件号：</span>
                    <span>{{ dispatchInfo.idNo }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="topTitle">物品信息</div>
            <div class="table">
              <div class="btn">
                <NButton
                  type="warning"
                  style="width: 115px"
                  class="btnExport"
                  @click="btnExport"
                >
                  模板导入
                </NButton>
                <NButton
                  type="warning"
                  style="width: 115px"
                  class="btnDownload"
                  @click="btnDownload"
                >
                  模板下载
                </NButton>
                <NButton
                  type="primary"
                  style="width: 115px"
                  class="btnAdd"
                  @click="add"
                >
                  添加
                </NButton>
              </div>
              <NDataTable
                :bordered="false"
                :columns="columns"
                :data="tableData"
                :pagination="false"
                striped
                :loading="tableLoading"
                :rowKey="rowKey"
                :checked-row-keys="rowKeys"
                @update:checked-row-keys="rowKeysChange"
              />
              <NButton
                tertiary
                type="error"
                style="width: 115px; margin-top: 10px"
                @click="BatchDelete"
              >
                批量删除
              </NButton>
              <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="start">
      <NButton
        style="width: 78px; color: #5fb17f"
        ghost
        @click="routeReplace"
      >
        <template #icon>
          <NImage
            :src="VBackImg"
            style="width: 50rem; height: 50rem"
            preview-disabled
          ></NImage>
        </template>
        返回
      </NButton>
    </NSpace>
  </FixedAction>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
  <NModal :auto-focus="false" v-model:show="modalVisibleExport">
    <SealApplicationFile
      :id="route.params.id"
      @getTableValue="getTableValue"
      @close="modalVisibleExport = false"
      @update="queryTableData()"
    ></SealApplicationFile>
  </NModal>
</template>
<script setup lang="ts">
import {
  NSpace,
  NButton,
  NScrollbar,
  NDataTable,
  useMessage,
  NSpin,
  NModal,
  NPagination,
  NImage
} from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { ref, h, reactive, onMounted } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import type { clueModel } from '@/api/clue'
import SealApplicationFile from './SealApplicationFile.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import useFlush from '@/hooks/useFlush'
import VBackImg from '@/assets/images/back.png'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
useFlush('flushClueTable', () => queryTableData())

const message = useMessage()
const loading = ref(false)
const modalVisibleExport = ref(false)
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const rowKey: any = (row: any) => row.id || ''
const rowKeys = ref([])
const columns: DataTableColumns = [
  {
    type: 'selection',
    fixed: 'left'
  },
  {
    title: '征集品名称',
    key: 'itemName',
    width: 120
  },
  {
    title: '类型',
    key: 'itemTypeName',
    width: 100
  },
  {
    title: '征集方式',
    key: 'collectTypeName',
    width: 100
  },
  {
    title: '接收时间',
    key: 'receiveTime',
    width: 100
  },
  {
    title: '接收人',
    key: 'receiveUser',
    width: 100
  },
  {
    title: '数量',
    key: 'itemNum',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id)
        },
        {
          default: () => '删除'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e)
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]

const tableLoading = ref(false)
const tableData = ref<clueModel[]>([])
const queryTableData = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<clueModel>>({
    module: 'clue',
    api: 'listItemsByClueId',
    override: {
      params: {
        id: route.params.id,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}
// 获取详情
const spinShow = ref(false)
const dispatchInfo = ref<any>({})
const getDispatchInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse<clueModel>>({
    module: 'clue',
    api: 'baseInfo',
    uri: {
      id: route.params.id as string
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  // @ts-ignore
  dispatchInfo.value = res.data
  // @ts-ignore
  // tableData.value = res.data.collectList ? res.data.collectList : []
  spinShow.value = false
}
//上传附件的数据
const getTableValue = (v: any) => {
  tableData.value = tableData.value.concat(v)
}
const handleEdit = (e: any) => {
  router.push({
    name: 'ClueOrganizationUpdate',
    params: { id: e.id, clueId: route.params.id },
    query: {
      type: 'update',
      redirect: route.fullPath
    }
  })
}
const handleDetail = (e: any) => {
  router.push({
    name: 'ClueOrganizationDetail',
    params: { id: e.id, clueId: route.params.id },
    query: {
      type: 'detail',
      redirect: route.fullPath
    }
  })
}
const add = () => {
  router.push({
    name: 'ClueOrganizationAdd',
    query: {
      type: 'add',
      redirect: route.fullPath
    }
  })
}
const ids = ref()
const idDDel=ref(false)
const modalVisible = ref(false)
const handleDelete = (id: any) => {
  ids.value = id
  idDDel.value=false
  modalVisible.value = true
}
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'deleteClueItem',
    override: {
      data: deleteId.value.length > 0&&idDDel.value ? deleteId.value : [ids.value]
    }
  })
  if (error) return message.error(error.message)
  queryTableData()
  modalVisible.value = false
  message.success('删除成功！')
  rowKeys.value = []
  deleteId.value = []
}
const deleteId = ref([])
const rowKeysChange = (v: any) => {
  rowKeys.value = v
  deleteId.value = v
}
const BatchDelete = () => {
  if (deleteId.value.length === 0) return message.warning('请至少选择一项！')
  idDDel.value=true
  modalVisible.value = true
}
const btnExport = () => {
  modalVisibleExport.value = true
}
const btnDownload = async () => {
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'downloadTemplate'
  })
  if (error) return message.error(error.message)
  download(headers, res)
}
//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}

onMounted(() => Promise.allSettled([getDispatchInfo(), queryTableData()]))
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;

      .basin-info {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: auto;
        border-bottom: 1px dashed #bc9e70;
        margin-bottom: 20rem;

        .basin-left {
          flex: 0 0 40%;
        }

        .box {
          display: flex;
          margin-bottom: 20rem;
          font-size: 16rem;

          span:first-child {
            display: inline-block;
            width: 120rem;
          }

          span:last-child {
            display: inline-block;
            flex: 1;
          }
        }
      }

      .approve {
        display: flex;
        width: 100%;
        margin-bottom: 20rem;
        border-bottom: 1px dashed #bc9e70;

        .box {
          display: flex;
          flex-direction: column;
          justify-content: center;
          min-width: 100rem;
          width: auto;
          height: 90rem;
          border-radius: 4px;
          border: 1px solid #d9d9d9;
          padding: 12rem;
          margin-right: 10rem;
          margin-bottom: 20rem;
        }
      }

      .table {
        width: 100%;
        background-color: #ebeceb;
        position: relative;

        .btn {
          background-color: transparent;
          position: absolute;
          right: 0;
          top: -43rem;

          .btnDownload {
            margin-left: 15px;
          }

          .btnAdd {
            margin-left: 15px;
          }
        }
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
